package com.zking.dao;

import java.util.List;

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import com.zking.entity.Permission;
import com.zking.entity.Role;
import com.zking.entity.UserInfo;

@Repository
public interface UserInfoDao {
	
	@Results(value={
		@Result(column="uid",property="uid",id=true),
		@Result(column="uid",property="roles",many=@Many(select="findRoleByUser",fetchType=FetchType.LAZY))
	},id="userMap")
	@Select("select * from userinfo")
	public List<UserInfo> selectAll();
	
	@ResultMap("userMap")
	@Select("select * from userinfo where uid=#{id}")
	public UserInfo selectByPrimaryKey(Integer id);
	
	@ResultMap("userMap")
	@Select("<script>select * from userinfo "+
	        "<where>"+
	        " <if test=\"username!=null\">and uname=#{username}</if>"+
			" <if test=\"password!=null\">and ident=#{password}</if>"+
			"</where></script>")
	public UserInfo selectByUserInfo(@Param("username")String username,@Param("password")String password);
	
	@Results(value= {
			   @Result(id=true,column="rid",property="rid"),
			   @Result(property="permissions",column="rid",many=@Many(fetchType=FetchType.LAZY,select="findPermissionByRole"))
	         },
			 id="roleMap"
	)
	@Select("select * from role where rid in (select roleid from userinfo_role where userid=#{id})")
	public List<Role> findRoleByUser(int id);
	
	@Select("select * from permission where pid in (select permissionid from role_permission where roleid=#{id})")
	public List<Permission> findPermissionByRole(int id);
	
	@Select("select * from permission")
	public List<Permission> findAllPermission();

}
